/*
 * Copyright 2010-2013 MaMuN
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package main.java.net.bornil.controller.admin;

import main.java.net.bornil.db.entity.admin.User;
import main.java.net.bornil.db.entity.admin.UserAvailabilityStatus;
import main.java.net.bornil.db.service.UserDao;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author MaMuN
 * @since Sep 22, 2012
 */
@Controller
@RequestMapping("/admin")
public class UserManagementController {
    private static Logger logger = Logger.getLogger(UserManagementController.class.getName());

    @Autowired
    private UserDao userService;

    /**
     * Name of the object that holds all information of event model
     */
    private static final String MODEL_USER = "user";

    @RequestMapping(method = RequestMethod.GET)
    public String get(Model model) {
        model.addAttribute(MODEL_USER, new User());
        return "admin/userMgmt";
    }

    /**
     * Creating or updating user account
     * 
     * @param user
     *            User information model
     * @param result
     *            Validation result to be displayed in the screen
     * @param model
     *            Model object to hold fetched values
     * 
     * @return Final view to be rendered.
     */
    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public String saveUser(@ModelAttribute(MODEL_USER) User user, BindingResult result, Model model) {
        if (user.isNew()) {
            if (user.getUserId() == null || user.getUserId().isEmpty()) {
                result.rejectValue("userId", "err.required", new String[] { "User ID" }, "");
            }
            if (user.getUserPass() == null || user.getUserPass().isEmpty()) {
                result.rejectValue("userPass", "err.required", new String[] { "User Password" }, "");
            }

            if (result.hasErrors()) {
                return "admin/userMgmt";
            }

            StandardPasswordEncoder spe = new StandardPasswordEncoder();
            user.setUserPass(spe.encode(user.getUserPass()));
            userService.createUser(user);
        } else {

        }

        // To clear all user information from the model
        user = new User();
        return "admin/userMgmt";
    }

    @RequestMapping(value = "/checkUserAvailability", method = RequestMethod.GET)
    public @ResponseBody
    UserAvailabilityStatus checkUserAvailability(@RequestParam String userId) {
        User user = userService.getUser(userId);

        if (logger.isDebugEnabled())
            logger.debug("User ID: " + user.getUserId());

        if (user.isNew())
            return UserAvailabilityStatus.available();
        return UserAvailabilityStatus.notAvailable(userId);

    }
}
